package net.oschina.android.api;

import java.util.HashMap;
import java.util.Map;

import net.oschina.android.app.AppContext;
import net.oschina.android.app.AppException;
import net.oschina.android.model.URLs;
import net.oschina.android.model.User;
import android.content.Context;

/**
 * @author HuangWenwei
 *
 * @date 2014年9月4日
 */
public class ApiClient {
	
	public static User login(Context context,String username,String pwd)throws AppException{
		Map<String, String> params = new HashMap<String,String>();
		params.put("username", username);
		params.put("pwd", pwd);
		params.put("keep_login", String.valueOf(1));
		
		AppContext appcontext = (AppContext) context.getApplicationContext();
		String loginUrl = URLs.LOGIN_VALIDATE_HTTP;
		if(appcontext.isHttpsLogin())
			loginUrl = URLs.LOGIN_VALIDATE_HTTPS;
		try {
			return User.parse(context, loginUrl, params);
		} catch (Exception e) {
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	public String _makeUrl(String pre_url,Map<String,Object>params){
		StringBuilder url = new StringBuilder(pre_url);
		if(url.indexOf("?")<0)
			url.append("?");
		for(String name:params.keySet()){
			url.append('&');
			url.append(name);
			url.append('=');
			url.append(String.valueOf(params.get(name)));
		}
		return url.toString().replace("?&", "?");
	}

}
